#include "capplication.h"

void CApplication::CreateWindow( const char * caption, int w, int h )
{
  
  if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
  {
	  
	  Log::Debug( "SDL could not initialize" );
	  return;
    
  }
  
  SDL_Surface * s = NULL;
  
  if( !( s = SDL_SetVideoMode( w, h, 32, SDL_DOUBLEBUF | SDL_OPENGL | SDL_HWSURFACE | SDL_HWACCEL ) ) )
  {
	  
	  Log::Debug( "SDL could not set its video mode" );
	  SDL_FreeSurface( s );
	  return;
    
  }
  
  SDL_FreeSurface( s );
  
  SDL_WM_SetCaption( NULL, caption );
  
  glViewport( 0, 0, w, h );
  
  Render::SetUp2DView();
  
  glEnable( GL_TEXTURE_2D );
  
  glShadeModel( GL_SMOOTH );
  
  glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
  
  glEnable( GL_DEPTH_TEST );
  glDepthFunc( GL_LEQUAL );
  
  glClearColor( 0.1f, 0.1f, 0.1f, 0.0f );
  glClearDepth( 1.0f );
 
  glEnable( GL_COLOR_MATERIAL );
  
  glEnable( GL_BLEND );
  glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
  
  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
  
			
  glewInit();
  
  Draw::InitDrawLists();
  Draw::InitOpenGL3Context();
  
}

CApplication::~CApplication()
{
	
	SDL_Quit();
	
	Draw::FreeDrawLists();
	Draw::FreeOpenGL3Context();
	
	delete m_pEntityFactory;
	
	delete m_pGraphicsFactory;
	
	delete m_pGameInterface;

    delete m_pStateFactory;
  
}

void CApplication::Init()
{
  
  Log::Debug( "Creating window" );
  
  CreateWindow( GAME_CAPTION, SCREEN_WIDTH, SCREEN_HEIGHT );
  
  Log::Debug( "Creating factories" );
  
  CreateFactories();
  
}

void CApplication::Run()
{
 
  Log::Debug( "Running application" );

  m_pStateFactory->SetCurrentState( ( CState * )m_pStateFactory->StateLine()->Find( "State2DRPG" ) );
  
  m_pStateFactory->Run();
  
}

void CApplication::CreateFactories()
{
  
  m_pStateFactory = new CStateFactory;
  m_pGraphicsFactory = new CGraphicsFactory;
  m_pEntityFactory = new CEntityFactory;
  
  m_pGameInterface = new CGameInterface;

  m_pGameInterface->SetFactories( m_pGraphicsFactory, NULL );

  m_pEntityFactory->SetEntityInterface( m_pGameInterface );
  m_pGameInterface->SetEntityFactory( m_pEntityFactory );
  
  m_pStateFactory->SetGameInterface( m_pGameInterface );
  
  m_pGameInterface->InitFontResources();
  m_pGameInterface->CreateSubSystems();
  m_pGameInterface->InitShaders();
  
  Draw::InitShaderValues( 0 );
  
}